package us.codecraft.webmagic.samples;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

/**
 * 描述: CSDN博客
 *
 * @outhor brozer
 * @email 798121446@qq.com
 * @create 2018-07-18 14:10
 */
public class CSDNBlogProcessor implements PageProcessor {

    public static final String URL_LIST = "https://blog\\.csdn\\.net/\\w+/article/list/\\d+\\?t=\\d+";

    public static final String URL_POST = "https://blog\\.csdn\\.net/\\w+/article/details/\\d+";

    public static TreeSet<String> urls=new TreeSet<>();

    public static TreeSet<String> pageUrls=new TreeSet<>();

    private Site site = Site
            .me()
            .setDomain("blog.csdn.net")
            .setSleepTime(3000)
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    @Override
    public void process(Page page) {
        //列表页
        if (page.getUrl().regex(URL_LIST).match()) {
            List<String> all = page.getHtml().xpath("//div[@class=\"article-list\"]").links().regex(URL_POST).all();
            urls.addAll(all);
            page.addTargetRequests(all);
            Selectable currentPageSelect = page.getHtml().regex("currentPage = \\d+");
            Selectable baseUrlSelect = page.getHtml().regex("baseUrl = 'https://blog\\.csdn\\.net/\\w+/article/list");
            Selectable pageSizeSelect = page.getHtml().regex("pageSize = \\d+");
            Selectable listTotalSelect = page.getHtml().regex("listTotal = \\d+");

            int currentPage = Integer.parseInt(currentPageSelect.toString().split(" = ")[1].trim());
            String baseUrl = baseUrlSelect.toString().split(" = ")[1].substring(1);
            int pageSize = Integer.parseInt(pageSizeSelect.toString().split(" = ")[1].trim());
            int total = Integer.parseInt(listTotalSelect.toString().split(" = ")[1].trim());
            int totalPage = total / pageSize;
            if(total%pageSize!=0){
                totalPage++;
            }
            for(int i=currentPage+1;i<=totalPage;i++){
                String listUrl = baseUrl + "/"+i+"?t=1";
                pageUrls.add(listUrl);
                page.addTargetRequest(listUrl);
            }
            //文章页
        } else {
            System.out.println("文章页面");
        }

    }

    @Override
    public Site getSite() {
        return Site.me().setDomain("blog.csdn.net");
    }

    public static void main(String[] args) {
        Spider.create(new CSDNBlogProcessor()).addUrl("https://blog.csdn.net/lixuanshengchao/article/list/1?t=1")
                .run();
    }
}
